import UserGameData from "./UserGameData";
import RankItem from "./RankItem";
import RankModel from "./RankModel";
import KVData from "./KVData";
import DataEvent from "./DataEvent";
/**
 * auth cgw
 */
const { ccclass, property } = cc._decorator;
export type RankMap = { key: string, value: RankModel[] };
@ccclass
export default class main extends cc.Component {


    // static PAGE_MAX_MEMBER: number = 50;//最多显示个数

    @property(cc.Prefab)
    prefab: cc.Prefab = null;

    @property(cc.Node)
    content: cc.Node = null;
    private rankMap: any = {}

    // private listView: ListView;
    // private pool: CCNodePool;
    private itemList:cc.Node[]  = []
    private key: string = DataEvent.RANK_KEY;


    private loadFinish: boolean = true;

    private MAX_NUM: number = 8; //每页最多显示人数
    private pageID: number = 0; // 页的id
    private maxPageNum:number = 0; // 需要显示多少页
    start() {
        // this.rankList = []
        this.node.active = false
        this.enabled = false
        if (typeof wx === 'undefined') {
            return;
        }
        // this.pool = new CCNodePool("RankItem", this.prefab, this.MAX_NUM)

        wx.onMessage(data => {
            if (data.message) {
                console.log('main data message is ================ ', data.message);
                if (data.message == DataEvent.HIDE_VIEW) {
                    this.node.active = false
                } else if (data.message == DataEvent.SHOW_VIEW) {
                    this.node.active = true;
                    if(data.value){
                        this.key = data.value;
                    }
                    this.updateData();
                } else if (data.message == DataEvent.SEND_DATA) {
                    let list = new Array()
                    list.push(new KVData(this.key, data.value))
                    this.setUserCloudStorage(list, () => {
                        console.log(' set user data success ')
                    })
                }else if(data.message == DataEvent.TURN_LEFT){
                    this.left();
                }else if(data.message == DataEvent.TURN_RIGHT){
                    this.right();
                }
            }
        });

        // this.initUserInfo('selfOpenId', (data) => {
        //     this.addData(data)

        // })

        // this.updateData();

    }

    updateData() {
        // console.log( ' updateData ')
        if (this.loadFinish) {
            this.loadFinish = false;
            this.pageID = 0;
            this.rankMap = {}
            this.initFriendInfo([this.key], (fData) => {
                // console.log(' fdata ',fData)
                this.addData(fData)
                this.maxPageNum = Math.ceil(this.rankMap[this.key].length / this.MAX_NUM)
                this.updateContent();
                this.loadFinish = true;

            })
        }

    }


    getSharedCanvas() {
        return wx.getSharedCanvas()
    }



    setUserCloudStorage(dataList: Array<KVData>, callback: Function) {
        // cc.log('setUserCloudStorage  ', dataList)
        wx.setUserCloudStorage({
            KVDataList: dataList,
            success: (res) => {
                callback(res.KVDataList)
            },
            fail: () => {
                console.warn('setUserCloudStorage fail ')
            },
            complete: () => {

            }
        })
    }



    getUserCloudStorage(keyList: Array<string>, callback: Function) {
        wx.getUserCloudStorage({
            keyList: keyList,
            success: (res) => {
                callback(res.KVDataList)
            },
            fail: () => {
                console.warn('getUserCloudStorage fail ')
            },
            complete: () => {

            }
        })
    }

    left(){
        this.pageID --;
        if(this.pageID < 0){
            this.pageID = this.maxPageNum - 1;
        }
        this.updateContent();
    }

    right(){
        this.pageID ++;
        if(this.pageID > this.maxPageNum - 1){
            this.pageID  = 0;
        }
        this.updateContent();
    }

    /**
     * 添加内容
     */
    updateContent() {
        let list = this.rankMap[this.key]
        if (!list) {
            return;
        }
        for (let index = 0; index < this.maxPageNum; index++) {
            let pos = index +  this.pageID * this.MAX_NUM
            let item = this.itemList[index]
            if(!item){
                item = cc.instantiate(this.prefab)
                this.itemList[index] = item;
                this.content.addChild(item)
            }
            this.updateListView(pos,item)
        }
 
    }


    updateListView(position: number, item: cc.Node) {
        // console.log(' position ',position)
        item.x = 0;
        let list = this.rankMap[this.key]
        if (list) {
            let rank = list[position]

            let comp: RankItem = item.getComponent('RankItem')
            if (comp) {
                if(rank){
                    comp.init(rank, position + 1)
                }else{
                    item.active = false;
                }                
               
            }
        }

        return item;
    }



    /**
     * 获得用户自己的数据
     * @param openID 
     * @param callback 
     */
    initUserInfo(openID: string = 'selfOpenId', callback: Function) {
        wx.getUserInfo({
            openIdList: [openID],
            lang: 'zh_CN',
            success: (res) => {

                callback(res.data)

                // this.createUserBlock(res.data[0]);
            },
            fail: (res) => {
                console.error(res);
            }
        });
    }

    /**
     * 添加数据
     * @param data 
     */
    addData(data: UserGameData[]) {
        if (!data) {
            return;
        }
        cc.log(' data.length =====================  ', data.length)
        let count = data.length
        for (let i = 0; i < count; i++) {
            const userData: UserGameData = data[i];
            let KVDataList = userData.KVDataList;
            if (KVDataList) {
                for (let index = 0; index < KVDataList.length; index++) {
                    const element: KVData = KVDataList[index];
                    if (!this.rankMap[element.key]) {
                        this.rankMap[element.key] = []
                    }
                    let value = JSON.parse(element.value)
                    this.rankMap[element.key].push(new RankModel(userData, value.wxgame.score))
                }
            }

        }
        for (const key in this.rankMap) {
            if (this.rankMap.hasOwnProperty(key)) {
                const element: RankModel[] = this.rankMap[key];
                element.sort((a, b) => {
                    return b.getScore() - a.getScore();
                })
            }
        }
    }

    /**
     * 获得好友数据
     * @param callback 
     */
    initFriendInfo(keyList, callback: Function) {
        wx.getFriendCloudStorage({
            keyList: keyList,
            success: (res) => {
                callback(res.data)
            },
            fail: (res) => {
                console.error(res);
            }
        });
    }

}
